package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbDict;
import com.bwie.service.TbDictService;
import com.bwie.mapper.TbDictMapper;
import com.bwie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_dict(字典表)】的数据库操作Service实现
* @createDate 2025-06-24 10:28:34
*/
@Service
public class TbDictServiceImpl extends ServiceImpl<TbDictMapper, TbDict>
    implements TbDictService{

    @Autowired
    TbDictMapper tbDictMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void loadDictList() {
        System.out.println("项目启动时，加载字典列表到缓存中");

        //  key=字典类型 value=[字典列表]
        // 使用redis的hashmap的数据类型

        List<TbDict> tbDictList = tbDictMapper.selectList(null);

        for (TbDict tbDict : tbDictList) {
            String key1 = "dict-"+tbDict.getDictType();
            String key2 = ""+tbDict.getDictId();

            stringRedisTemplate.opsForHash().put(key1, key2, JSON.toJSONString(tbDict));
        }

        System.out.println("加载字典列表完成");

    }

    @Override
    public R getDictList(Integer typeId) {
        //--1 检查缓存中是否存在
        String key1 = "dict-"+typeId;
        Boolean hasKey = stringRedisTemplate.hasKey(key1);
        if(hasKey) {
            System.out.println("从缓存中读取字典列表");

            List<Object> objectList = stringRedisTemplate.opsForHash().values(key1);

            ArrayList<TbDict> list = new ArrayList<>();
            for (Object object : objectList) {
                TbDict tbDict = JSON.parseObject(object.toString(), TbDict.class);
                list.add(tbDict);
            }

            return R.ok().setData(list);
        }


        //--2 缓存中不存在，从数据库中读取
        System.out.println("从数据库中读取字典列表");
        List<TbDict> tbDictList = tbDictMapper.selectList(
                new QueryWrapper<TbDict>().lambda().eq(TbDict::getDictType, typeId)
        );

        // 把字典列表放入缓存
        for (TbDict tbDict : tbDictList) {
            key1 = "dict-"+tbDict.getDictType();
            String key2= ""+tbDict.getDictId();
            stringRedisTemplate.opsForHash().put(key1, key2, JSON.toJSONString(tbDict));
        }

        return R.ok().setData(tbDictList);
    }
}




